import { createStore } from 'vuex'
import axios from 'axios'

const store = createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || null,
    votes: [],
    news: [],
    announcements: []
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    clearAuth(state) {
      state.user = null
      state.token = null
      localStorage.removeItem('token')
    },
    setVotes(state, votes) {
      state.votes = votes
    },
    setNews(state, news) {
      state.news = news
    },
    setAnnouncements(state, announcements) {
      state.announcements = announcements
    }
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        const response = await axios.post('http://localhost:8080/api/auth/login', credentials)
        commit('setToken', response.data.accessToken)
        return response
      } catch (error) {
        throw error
      }
    },
    async register({ commit }, userData) {
      try {
        const response = await axios.post('http://localhost:8080/api/auth/register', userData)
        return response
      } catch (error) {
        throw error
      }
    },
    async fetchVotes({ commit }) {
      try {
        const response = await axios.get('http://localhost:8080/api/vote/active')
        commit('setVotes', response.data)
        return response
      } catch (error) {
        throw error
      }
    },
    async castVote({ commit }, voteData) {
      try {
        const response = await axios.post('http://localhost:8080/api/vote/cast', voteData)
        return response
      } catch (error) {
        throw error
      }
    },
    async fetchNews({ commit }) {
      try {
        const response = await axios.get('http://localhost:8080/api/news')
        commit('setNews', response.data)
        return response
      } catch (error) {
        throw error
      }
    },
    async fetchAnnouncements({ commit }) {
      try {
        const response = await axios.get('http://localhost:8080/api/announcements')
        commit('setAnnouncements', response.data)
        return response
      } catch (error) {
        throw error
      }
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    currentUser: state => state.user,
    activeVotes: state => state.votes,
    latestNews: state => state.news.slice(0, 5),
    latestAnnouncements: state => state.announcements.slice(0, 5)
  }
})

// Add axios interceptor for authentication
axios.interceptors.request.use(
  config => {
    const token = store.state.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

export default store
